package com.hycat.mail.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.hycat.mail.common.exception.MailException;
import com.hycat.mail.common.model.ExceptionEnum;
import com.hycat.mail.common.model.JwtInfo;
import com.hycat.mail.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author 吕泽浩业
 * @version 1.0
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(HandlerInterceptor.class);

    public static ThreadLocal<JwtInfo> threadLocal = new ThreadLocal<>();

    //TODO   用户访问授权接口就刷新token:第一个拦截器做threadLocal和刷新，第二个拦截器进行threadLocal判断
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //1.解析request中token
        String jwtInfoStr = JwtUtil.getMemberIdByJwtToken(request);
        JwtInfo jwtInfo;
        try {
            jwtInfo = JSON.parseObject(jwtInfoStr, JwtInfo.class);
        } catch (Exception e) {
            throw new MailException(ExceptionEnum.MEMBER_NOT_LOGIN);
        }
        //2.token存在,保存threadLocal
        if(!Objects.isNull(jwtInfo)) {
            threadLocal.set(jwtInfo);
            logger.info("本次登录成功 携带的信息是 {}" , JSON.toJSONString(jwtInfo));
            return true;
        } else {
        //3.token不存在,抛异常
            throw new MailException(ExceptionEnum.MEMBER_NOT_LOGIN);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
